<?php

declare(strict_types=1);

namespace App\User\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Controller\AbstractController;
use App\Common\Middleware\JwtAuthMiddleware;
use App\Common\Middleware\PermissionMiddleware;
use App\Third\Service\Kz\KzMainService;
use App\User\Request\MemberRequest;
use App\User\Service\MemberService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * @Controller()
 */
class MemberController extends AbstractController
{

    /**
     * @Inject()
     * @var MemberService
     */
    private $memberService;

    /**
     * @Inject()
     * @var KzMainService
     */
    private $kzMainService;

    /**
     * 获取会员列表
     * @RequestMapping(path="/v1/member", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param MemberRequest $memberRequest
     *
     * @return array
     */
    public function list(MemberRequest $memberRequest)
    {
        $params = $memberRequest->all();
        $field = [
            'store_member.mid',
            'store_member.phone',
            'store_member.nickname',
            'store_member.gender',
            'FLOOR(DATEDIFF(CURDATE(), store_member.birthday)/365.2422) as age',
            'store_member.register_date',
            'store_member.tags',
            'store_member.source',
            'store_member.status',
            'store_member.kz_cus_code',
            'order.buy_num',
            'order.total_amount',
            'order.unit_price',
            'order.without_order_day'
        ];
        $list = $this->memberService->getMemberList($params, $field);
        if (isset($params['perpage']) && !empty($params['perpage'])) {
            return $this->success($list->items(), '获取会员列表成功', $list->total());
        } else {
            return $this->success($list, '获取会员列表成功', $list->count());
        }


    }

    /**
     * 会员详情
     *
     * @RequestMapping(path="/v1/member/{id:\d+}", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     *
     * @return array
     */
    public function Info(int $id)
    {
        $where = ['mid' => $id];
        $field = [
            'mid',
            'phone',
            'nickname',
            'gender',
            'birthday',
            'tags',
            'kz_cus_code'
        ];
        $result = $this->memberService->find($where, $field);
        return $this->success($result, '获取会员信息成功');
    }

    /**
     * 会员加标签
     *
     * @PutMapping(path="/v1/member/{id:\d+}", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     *
     * @return array
     */
    public function update(int $id)
    {
        // 标签ID 字符串
        $tags = $this->request->input('tags', '');
        if (empty($tags)) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $update = ['tags' => $tags];
        try {
            $this->memberService->update((int)$id, $update);
        } catch (\Exception $e) {
            return $this->failed(ErrorCode::SERVER_ERROR);
        }
        return $this->success([], '加标签成功');
    }

    /**
     * 小程序个人中心
     *
     * @RequestMapping(path="/v1/api/member/center", methods="get")
     * @return array
     */
    public function userCenter(){
        $params = $this->request->all();
        if (!is_numeric($params['mid']) || empty($params['event'])){
            return $this->failed(ErrorCode::SYSTEM_INVALID, "参数错误");
        }
        switch ($params['event']) {
            case 'info':
                $res = $this->memberService->mainData($params);
                break;
            case 'edit':
                $where = ['mid' => $params['mid']];
                $field = ['mid','phone','nickname','gender','birthday','face_url'];
                $res = $this->memberService->findFirst($where, $field);
                return $this->success($res, '获取会员资料成功');
                break;
            default:
        }
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success($res['data'], $res['msg']);
    }

    /**
     * 小程序个人中心--修改资料
     * @PutMapping(path="/v1/api/member/{mid:\d+}", methods="put")
     * @param int $mid
     * @return array
     */
    public function modify(int $mid)
    {
        $params = $this->request->all();
        foreach ($params as $k => $v){
            if (empty($v)){
                return $this->failed(ErrorCode::SYSTEM_INVALID, "提交信息不完整");
            }
        }
        try {
            $data = [
                'nickname' => $params['nickname'],
                'gender' => $params['gender'],
                'birthday' => $params['birthday'],
                'face_url' => $params['face_url']
            ];
            $this->memberService->update((int)$mid, $data);
        } catch (\Exception $e) {
            return $this->failed(ErrorCode::NOT_IN_FORCE, $e->getMessage());
        }
        return $this->success([], '提交成功');
    }

    /**
     * 客至会员信息--会员码
     * @RequestMapping(path="/v1/api/member/barcode", methods="get")
     */
    public function cusInfo()
    {
        $param = $this->request->all();
        if (!is_numeric($param['mid'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID, '登陆信息失效,请重新登陆噢');
        }
        $membInfo = $this->memberService->findFirst(['mid' => $param['mid']]);
        if (empty($membInfo->kz_cus_code)){
            $res = $this->memberService->addCusInfo($membInfo->toArray(), $membInfo->phone);
            $cusCode = $res['data']['cusCode'];
            $membInfo->kz_cus_code = $cusCode;
        }else{
            $cusCode = $membInfo->kz_cus_code;
        }
        $res = $this->kzMainService->getCusInfo($cusCode);
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        // 写入 weChat openID
        if (empty($membInfo->wx_openid) && isset($res['data']['cusInfo']['fMemberQrCode'])){
            $membInfo->wx_openid = $res['data']['cusInfo']['fMemberQrCode'];
        }
        $membInfo->save();
        $data = [
            'cusLevelName' => $res['data']['cusInfo']['cusLevelName'],
            'cusCode' => $res['data']['cusInfo']['cusCode'],
            'balanceScore' => $res['data']['cusInfo']['core'],
            'balanceMoney' => $res['data']['cusInfo']['accountMoney']
        ];
        return $this->success($data, $res['msg']);
    }

    /**
     * 会员消费摘要
     * @RequestMapping(path="/v1/api/member/consumption", methods="get")
     * @return array
     */
    public function consumption(){
        $param = $this->request->all();
        foreach ($param as $k => $v){
            if ($k == 'platformConfidential') continue;
            if (!is_numeric($v)) return $this->failed(ErrorCode::SYSTEM_INVALID, "{$k}参数错误");
        }
        $cusCode = $cusCode = $this->memberService->findValue(['mid' => $param['mid']], 'kz_cus_code');
        $res = $this->kzMainService->summary($cusCode, (int)$param['page'], (int)$param['perpage']);
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success($res['data'], $res['msg'], $res['data']['total']);
    }

    /**
     * 个人中心--会员优惠券
     * label 0未使用券，1已使用优惠券，2已过期优惠券
     * @RequestMapping(path="/v1/api/member/coupon", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class)
     * })
     * @return array
     */
    public function couponList(){
        $request = $this->request;
        $mid = $request->getAttribute('mid');
        $label = $request->input('label');
        $page = $request->input('page',1);
        $pageSize = $request->input('perpage',10);
        if (!is_numeric($label) || !is_numeric($page) || !is_numeric($pageSize)){
            return $this->failed(ErrorCode::SYSTEM_INVALID, "参数错误");
        }
        $cusCode = $this->memberService->findValue(['mid' => $mid], 'kz_cus_code');
        $res = $this->kzMainService->memberCouponsByCusInfo($cusCode, (int)$label, 0, 0);
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success($res['data'], $res['msg']);
    }

    /**
     * 获取会员绑定的微信手机号
     * @RequestMapping(path="/v1/api/wechat/phone", methods="get")
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @author liule
     */
    public function weChatPhone(){
        $encryptedData = $this->request->input('encryptedData');
        $iv = $this->request->input('iv');
        $encode = $this->request->input('encode');
        if (!$encryptedData || !$iv) {
            return $this->failed(ErrorCode::SYSTEM_INVALID, "参数错误");
        }
        $res = $this->memberService->getMemberInfoByWeChatPhone($iv, $encryptedData, $encode);
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success($res['data'], $res['msg']);
    }

    /**
     * 输入手机号登录
     * @return array
     * @RequestMapping(path="/v1/api/member/login", methods="post")
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function memberLoginByInputPhone(){
        $encode = $this->request->input('encode');
        $phone = $this->request->input('phone');
        $code = $this->request->input('code');
        $res = $this->memberService->memberLoginByInputPhone($phone, $code, $encode);
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success($res['data'], $res['msg']);
    }

}
